﻿using OA.Infrastructure.Authentication.Redis;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;

namespace OA.Infrastructure.Authentication;

internal class PersistedGrantStore : IPersistedGrantStore
{
    private readonly ILogger<PersistedGrantStore> _logger;
    private readonly RedisClient _cache;

    public PersistedGrantStore(
        RedisClient redisClient,
        ILogger<PersistedGrantStore> logger)
    {
        _cache = redisClient;
        _logger = logger;
    }

    public async Task StoreAsync(PersistedGrant token)
    {
        try
        {
            await _cache.SetAsync(token.Key, token, new DistributedCacheEntryOptions(), cancellationToken: default);

            _logger.LogDebug("尝试在 Redis 中保存或更新Token key：{persistedGrantKey}", token.Key);
        }
        catch (Exception ex)
        {
            _logger.LogError(0, ex, "存储持久化授权时发生异常");
            throw;
        }
    }

    public async Task<PersistedGrant> GetAsync(string key)
    {
        var model = await _cache.GetAsync<PersistedGrant>(key);

        _logger.LogDebug("Redis中找到Key：{key}？: {persistedGrantKeyFound}", key, model != null);

        return model;
    }

    public Task<IEnumerable<PersistedGrant>> GetAllAsync(PersistedGrantFilter filter)
    {
        throw new NotImplementedException();
    }

    public Task RemoveAsync(string key)
    {
        return _cache.RemoveAsync(key);
    }

    public Task RemoveAllAsync(PersistedGrantFilter filter)
    {
        throw new NotImplementedException();
    }
}